package com.maoslv.service.good;

import com.maoslv.mapper.GoodsMapper;
import com.maoslv.pojo.Goods;
import com.maoslv.pojo.Order;
import com.maoslv.pojo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService{
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> getGoodsList(Pagination pagination) {
        pagination.setCurrentPage((pagination.getCurrentPage() - 1) * pagination.getPageSize());
        Integer total = goodsMapper.getTotal(pagination);
        List<Goods> goodsList = goodsMapper.getGoodsList(pagination);
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("goodsList", goodsList);
        return result;
    }

    @Override
    public int addGoods(Goods goods) {
        goods.setState(true);
        return goodsMapper.addGoods(goods);
    }

    @Override
    public Goods getGoodsInfo(Integer id) {
        return goodsMapper.getGoodsInfo(id);
    }

    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateGoods(goods);
    }

    @Override
    public List<Goods> getShopCarGoods() {
        return goodsMapper.getShopCarGoods();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateGoods(List<Goods> goodsList) {
        List<Integer> idList = new ArrayList<>();

        goodsList.forEach(goods -> {
            idList.add(goods.getId());
        });
        List<Goods> goodsListById = goodsMapper.getGoodsListById(idList);
        goodsMapper.delGoods(idList);
        goodsListById.forEach(oldGoods -> {
            goodsList.forEach(newGoods -> {
                if (oldGoods.getId().equals(newGoods.getId())) {
                    oldGoods.setStock(oldGoods.getStock() - newGoods.getNum());
                }
            });
        });
        return goodsMapper.batchAddGoods(goodsListById);
    }
}
